#
# used by scripts to push/pull values to/from iPhoto
#


from Foundation import *
from AppKit import *
from ScriptingBridge import SBApplication
from objc import ivar

import os
import pdb

from helpers import log
from FileNode import FileNode



# Strings for figuring out where things are in the iPhoto library directory
photoFolder = os.path.expanduser("~/Pictures/Photos").rstrip("/")
libPath = None
mod_dir = "Modified"
orig_dir = "Originals"


def setPhotoFolder(folder):
	global photoFolder
	folder = os.path.expanduser(folder).rstrip("/")
	if os.path.exists(folder):
		photoFolder = folder
	else:
		raise Exception, "Folder does not exist"

class IPhotoNode(object):
	# list of tuples to automate the code:
	# self.[1] = src.[2]() 
	attrs = (
		("path",    "imagePath"),
		("name",    "imageFilename"),
		("comment", "comment"),
		)
	
	def __init__(self, src):
		global libPath, mod_dir, orig_dir, photoFolder
		self.src = src
		self.desc = "OK"

		self.path = None
		self.origPath = None
		self.dir = None
		self.keys = ""
		
		# extract info from iPhoto
		for (sName, func) in self.attrs:
			setattr(self, sName, getattr(self.src, func)())
			log("self", sName, " set to: ", getattr(self,sName))

		self.path = getCanonicalPathName(self.path)
		self.dir = os.path.basename(os.path.dirname(self.path))
		self.keywordArray = [str(x.name()) for x in src.keywords()]
		self.keys = ", ".join(self.keywordArray)
		log("keys = ", self.keys)
		
		# set the libPath, if we haven't already:
		if libPath is None and not (self.path is None):
			libLen = self.path.find(mod_dir)
			if libLen < 0:
				libLen = self.path.find(orig_dir)
			if libLen >= 0:
				libPath = self.path[:(libLen-1)]
				log("libPath has been set to: ", libPath)

		# if it's modified, get the original
		if not self.path.startswith(photoFolder):
			if ("/" + mod_dir + "/") in self.path:
				self.origPath = self.path.replace("/"+mod_dir+"/", "/" + orig_dir + "/", 1)
				self.path = getCanonicalPathName(self.origPath)
				log(self.path)
			
			if not self.path.startswith(photoFolder):
				raise Exception, "not in the right folder"
			

		log("self path done")
	
	def setComment(self, c):
		self.src.comment = c
	
	def fileNode(self):
		return FileNode.alloc().initWithPath_(self.path)
		


def getIPhotoSelection():
	global photoFolder
	photoFolder = os.path.expanduser(photoFolder).rstrip("/")
	if photoFolder is None or not os.path.exists(photFolder):
		raise Exception, "photoFolder is invalid"
	
	okPhotos = []
	
	iPhoto = SBApplication.applicationWithBundleIdentifier_("com.apple.iPhoto")
	allPhotos = iPhoto.selection()

	numPhotos = len(allPhotos)
	log("Scanning ", numPhotos, " selected photos")
	
	for photo in allPhotos:
		try:
			p = IPhotoNode(photo)
			okPhotos.append(p)
		except Exception,e:
			log("An error occurred:", e)

	return okPhotos



def getCanonicalPathName(filePath):
	if filePath is None:
		return None
	p = os.popen('osascript -e \'\
		tell application "Finder"\n\
			set f to ("' + filePath + '" as POSIX file)\n\
			set n to 0\n\
			repeat while class of f is alias file\n\
				if n is less than 5 then\n\
					set n to n + 1\n\
					set f to original item of f\n\
				end if\n\
			end repeat\n\
			try\n\
				return POSIX path of (f as alias) as string\n\
			on error\n\
				return POSIX path of f as string\n\
			end try\n\
		end tell\'')
	res = str(p.readlines()[0].strip())
	if res is None:
		log("res is None!")
		return filePath
	if not res.startswith("/"):
		log("does not start with a slash: ", res)
		raise Exception, "getCanonicalPathName failed"
	return res
